package com.zidian.study.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.zidian.study.Application.MyApplication;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.utils.CommonDialogUtil;
import com.zidian.study.utils.SharedPreferenceUtils;
import com.zidian.study.utils.ToastUtil;
import com.zidian.study.wheel.NumericWheelAdapter;
import com.zidian.study.wheel.WheelView;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import greenDAO.bean.StudyWeek;
import greenDAO.dao.DaoSession;
import greenDAO.dao.StudyWeekDao;
import com.zidian.student.trucks.R;

/**
 * className：
 * 作者：xjc on 2016/8/21 11:32
 * 邮箱：1475977630@qq.com
 */
public class CourseFragment extends BaseFragment {

    /**
     * 判断跳转到哪个页面的下标
     */
    private int switchid = 0;
    /**
     * Fragment管理器
     */
    private FragmentManager fragmentManager;

    /* ============Control================= */
    /**
     * 按钮的单击监听
     */
    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup arg0, int keyCode) {
            /* 处理之前的文字 */
            ((RadioButton) arg0.getChildAt(switchid)).setTextColor(0xff7f7f7c);
            /* 处理被单击的按钮 */
            RadioButton mRadioButton = (RadioButton) arg0.findViewById(keyCode);
            mRadioButton.setTextColor(0xff25c17f);

            switchid = Integer.parseInt(mRadioButton.getTag().toString());
            /* 设置跳转那个fragment页面 */
            switch (switchid) {
                case 0:
                    weekSetting.setVisibility(View.VISIBLE);
                    menu.setVisibility(View.GONE);
                    addChildFragment(CourseTableFragment.newInstance(currentWeek));
                    break;
                case 1:
                    weekSetting.setVisibility(View.GONE);
                    menu.setVisibility(View.GONE);
                    addChildFragment(CourseClassFragment.newInstance());
                    break;
            }

        }

    };

    public AlertDialog mDialogView;
    private ImageView menu;

    private TextView weekSetting;
    private WheelView weekCount;
    private TextView mBtnDateConfirm;
    private TextView mBtnCancel;
    private DaoSession daoSession;
    private int currentWeek = -1;

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        menu = (ImageView) view.findViewById(R.id.course_menu);
        //暂时隐藏分享
        menu.setVisibility(View.GONE);
        weekSetting = (TextView) view.findViewById(R.id.course_week);

        weekSetting.setVisibility(View.VISIBLE);

        daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
        StudyWeekDao weekDao = daoSession.getStudyWeekDao();

        if (SharedPreferenceUtils.getCurrentWeek() == 0) {
            weekSetting.setText("请选择周次");
        } else {
            weekSetting.setText("第" + SharedPreferenceUtils.getCurrentWeek() + "周");
            currentWeek = SharedPreferenceUtils.getCurrentWeek();
        }
        //添加首个Fragment
        BaseFragment firstFragment = CourseTableFragment.newInstance(currentWeek);
        addChildFragment(firstFragment);

        menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(getActivity(), menu);
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.share:
                                showShare();
                                viewSaveToImage(getView());

                                break;
                        }
                        return true;
                    }
                });
                //使用反射，强制显示菜单图标
                try {
                    Field[] fields = popup.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        if ("mPopup".equals(field.getName())) {
                            field.setAccessible(true);
                            Object menuPopupHelper = field.get(popup);
                            Class<?> classPopupHelper = Class.forName(menuPopupHelper
                                    .getClass().getName());
                            Method setForceIcons = classPopupHelper.getMethod(
                                    "setForceShowIcon", boolean.class);
                            setForceIcons.invoke(menuPopupHelper, true);
                            break;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                popup.inflate(R.menu.menu_main);
                popup.show();
            }
        });

        weekSetting.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clickBirthday();
            }
        });


    }


    private void showShare() {
        ShareSDK.initSDK(mActivity);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(mActivity);
    }

    public void viewSaveToImage(View view) {

        verifyStoragePermissions(mActivity);

        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        FileOutputStream fos;
        try {
            // 判断手机设备是否有SD卡
            boolean isHasSDCard = Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED);
            if (isHasSDCard) {
                // SD卡根目录
                File sdRoot = Environment.getExternalStorageDirectory();
                File file = new File(sdRoot, "test.PNG");
                if (file.exists()) {
                    file.delete();
                }
                fos = new FileOutputStream(file);
                cachebmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
            } else
                throw new Exception("创建文件失败!");

//            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        view.destroyDrawingCache();
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }


    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * Checks if the app has permission to write to device storage
     * <p/>
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public static CourseFragment newInstance() {
        return new CourseFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.tab_fargment_course;
    }

    /**
     * 选择周
     */
    private void clickBirthday() {
        mDialogView = CommonDialogUtil.getCommonDialog(getActivity(),
                R.layout.item_course_week, Gravity.BOTTOM);
        weekCount = (WheelView) mDialogView.findViewById(R.id.id_week);
        mBtnDateConfirm = (TextView) mDialogView.findViewById(R.id.btn_confirm);
        mBtnCancel = (TextView) mDialogView.findViewById(R.id.btn_cancel);
        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogView.dismiss();
            }
        });
        mBtnDateConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectedResult();
            }
        });
        setUpDataDate();
    }

    /**
     * 更新日期数据
     **/
    private void setUpDataDate() {
        getDataPick();
        weekCount.setVisibleItems(7);

    }

    private void getDataPick() {
        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(
                getActivity(), 1, 24);
        numericWheelAdapter1.setLabel("周");
        weekCount.setViewAdapter(numericWheelAdapter1);
        weekCount.setCyclic(true);
        weekCount.setCurrentItem(currentWeek - 1);

    }

    /**
     * 显示最后的时间和地址的结果
     */
    private void showSelectedResult() {
        int curWeek = weekCount.getCurrentItem() + 1;
        Log.e("c", currentWeek + "  " + curWeek);
        if (currentWeek != curWeek) {
            currentWeek = curWeek;
            weekSetting.setText("第" + curWeek + "周");
            Calendar cal = Calendar.getInstance();
            int weekIndex = cal.get(Calendar.WEEK_OF_YEAR);

            SharedPreferenceUtils.setCurrentWeek(curWeek);
            removeChildFragment();
            addChildFragment(CourseTableFragment.newInstance(curWeek));
//            ToastUtil.showToast(mActivity.getApplication(), curWeek + "");
        }
        mDialogView.dismiss();

    }

    //移除fragment
    protected void removeChildFragment() {
        getChildFragmentManager().popBackStack();
        BaseFragment firstFragment = CourseTableFragment.newInstance(0);
        addChildFragment(firstFragment);
    }

    //添加fragment
    protected void addChildFragment(BaseFragment fragment) {
        if (fragment != null) {
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.course_contentview, fragment, fragment.getClass().getSimpleName())
                    .addToBackStack(fragment.getClass().getSimpleName())
                    .commitAllowingStateLoss();
        }
    }
}
